#!/usr/local/php/bin/php
<?php

$data_source = 'done_100.txt';
$data_source = $argv[1];
//print_r($argv);
if (file_exists($data_source))
{
	$fp = fopen($data_source, 'r');
}
else
{
	die($data_source.' is not exist!\n');
}
if (!$fp)
{
	echo "Error: open {$data_source}";
	exit(0);
}
else
{
	$i = 0;
	$arr_data = array();
	$arr_hash_key = array();
	$info = "start time: ".date('Y-m-d H:i:s');
	while (!feof($fp))
	{
		$ori_data = fgets($fp);
		//echo $ori_data.'-------';

		$arr_ori_data = explode("\t", $ori_data);
		$hash_key = base64_encode($arr_ori_data[0]);
//		array_push($arr_hash_key, $hash_key);
		if (!empty($ori_data))
		{
			if (array_key_exists($hash_key, $arr_data))
			{
				// combine it
				$arr_ori_val = explode("\t", $arr_data[$hash_key]);
				$arr_ori2 = $arr_ori_val[1] + $arr_ori_data[1];
				$arr_ori3 = $arr_ori_val[2] + $arr_ori_data[1];
				$arr_data[$hash_key] = $arr_ori_val[0]."\t".$arr_ori2."\t".$arr_ori3."\n";	
			}	
			else
			{
			
				$arr_data[$hash_key] = $ori_data;
			}
			$i++;
		}	
	}
	fclose($fp);
	echo "sum=$i\n";

	$arr_row_data = array();
	$arr_sum_stat = array(
		'click' => 0,
		'valid_click' => 0,
	);

	$f = fopen("hash_".$data_source, 'w');
	foreach ($arr_data AS $key => $val)
	{
		$arr_row_data = explode("\t", $val);
		$arr_sum_stat['click'] += $arr_row_data[1];
		$arr_sum_stat['valid_click'] += $arr_row_data[2];
		fwrite($f, $key."\t".$val);
	}
	fclose($f);
//	print_r($arr_sum_stat);
	file_put_contents("sum_hash_".$data_source, implode("\t", $arr_sum_stat));
	//file_put_contents('hash_'.$data_source, implode("\n", $arr_data));
	//print_r($arr_data);
	echo "arr_hash_key count =".count($arr_data)."\n";
//	array_pop($arr_data);	
//	ksort($arr_data);
//	print_r($arr_data);
//	echo "count=".count($arr_data);
/*	die("br");
	if (!$f = fopen('s_'.$data_source, 'w'))
	{
		die('sorted file open error\n');	
	}
	else
	{
		foreach ($arr_data AS $key => $row)
		{
			$row_data = $key."\t".$row;	
			echo $row_data."<br>";
		}
	}
	fclose($f);
*/	$info .= "\nend time: ".date('Y-m-d H:i:s');
	echo "$info\n";
	file_put_contents("log/".date('H_i_s').".txt", $info);
}	

?>
